package com.hy.controller;

import com.hy.common.Result;
import com.hy.entity.User;
import com.hy.service.UserService;
import com.hy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/back/auth")
public class AuthController {

    @Autowired()
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestParam String openid) {
        // 根据openid查询用户
        User user = userService.getByOpenid(openid);
        
        // 如果用户不存在，则自动注册
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setPoints(0);
            userService.save(user);
        }
        
        // 生成token
        String token = jwtUtil.generateToken(openid, user.getId());
        
        // 返回用户信息和token
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);
        
        return Result.success(map);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> info(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        return Result.success(userService.getById(userId));
    }
} 